package com.fx.zmlzml.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.fx.zmlzml.common.response.Result;
import com.fx.zmlzml.constant.SysConstants;
import com.fx.zmlzml.domain.dto.SysUserDetailDTO;
import com.fx.zmlzml.entity.SysUser;
import com.fx.zmlzml.mapper.SysUserMapper;
import com.fx.zmlzml.service.SysService;
import com.fx.zmlzml.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SysServiceImpl implements SysService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result<Map<String, String>> login(SysUser sysUser) {
        // AuthenticationManager 进行认证
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword()));
        if (authenticate == null) {
            return Result.error("用户名或密码错误");
        }
        SysUserDetailDTO user = (SysUserDetailDTO) authenticate.getPrincipal();
        String token = createLoginToken(user.getUserId());
        // 缓存 Token
        redisUtil.setObjectWithExpire(SysConstants.LOGIN_TOKEN_PREFIX + user.getUserId(), user, SysConstants.LOGIN_TOKEN_EXPIRE); // 缓存 Token 1小时
        Map<String, String> result = new HashMap<>();
        result.put("token", token);
        return Result.success(result);
    }

    @Override
    public boolean userExists(String username) {
        if (sysUserMapper.selectByUsername(username) != null) {
            return true;
        }
        return false;
    }

    @Override
    public boolean register(SysUser sysUser) {

        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));

        if (sysUserMapper.insert(sysUser) > 0) {
            return true;
        }
        return false;
    }


    /**
     * 创建登录 Token
     */
    public String createLoginToken(Long userId) {
        Map<String, Object> payload = new HashMap<>();

        // 标准声明
        payload.put("iss", "zmlzml");     // 签发者
        payload.put("sub", "authentication");    // 主题
        payload.put("iat", System.currentTimeMillis() / 1000); // 签发时间
        payload.put("exp", System.currentTimeMillis() / 1000 + 3600); // 1小时后过期

        // 用户信息（只放必要信息）
        payload.put("userId", userId);
        payload.put("role", "admin");     // 角色权限

        // 业务相关声明
        payload.put("loginTime", System.currentTimeMillis());

        return JWTUtil.createToken(payload, SysConstants.SECRET_KEY.getBytes());
    }

}
